﻿using System;
using System.Collections.ObjectModel; // ObservableCollection 用于数据绑定
using System.Threading.Tasks; // 用于异步操作
using WPFServices.Commands; // 引入自定义命令类
using WPFServices.Models; // 引入通用模型
using WPFServices.Models.Domain; // 引入领域模型
using WPFServices.Services.DomainService.Role;

namespace WPFServices.ViewModels.DomainViewModel.RoleViewModels // ViewModel 命名空间
{
    // RoleViewModel：角色管理界面的 ViewModel，处理数据和逻辑。
    // 继承 BaseViewModel 以支持属性变更通知。
    public class RoleViewModel : BaseViewModel
    {
        private readonly RoleService _roleService; // 角色数据服务
        private ObservableCollection<RoleDto> _roles; // 角色列表
        private RoleDto _selectedRole; // 当前选中的角色
        private bool _isLoading; // 数据加载状态
        private string _searchRoleName; // 搜索关键词
        private int _currentPage = 1; // 当前页码
        private int _pageSize = 10; // 每页大小
        private int _totalCount; // 总记录数
        private int _totalPages; // 总页数

        // 构造函数：初始化服务、集合和所有命令。
        public RoleViewModel()
        {
            _roleService = new RoleService();
            Roles = new ObservableCollection<RoleDto>();

            // 初始化命令，绑定到相应的方法。
            LoadDataCommand = new RelayCommand(async _ => await LoadRolesAsync());
            SearchCommand = new RelayCommand(async _ => await SearchRolesAsync());
            AddCommand = new RelayCommand(_ => AddRole());
            EditCommand = new RelayCommand(_ => EditRole(), _ => SelectedRole != null);
            DeleteCommand = new RelayCommand(async _ => await DeleteRoleAsync(), _ => SelectedRole != null);
            FirstPageCommand = new RelayCommand(_ => GoToFirstPage(), _ => CurrentPage > 1);
            PreviousPageCommand = new RelayCommand(_ => GoToPreviousPage(), _ => CurrentPage > 1);
            NextPageCommand = new RelayCommand(_ => GoToNextPage(), _ => CurrentPage < TotalPages);
            LastPageCommand = new RelayCommand(_ => GoToLastPage(), _ => CurrentPage < TotalPages);

            // 自动加载初始数据。
            _ = SearchRolesAsync();
        }

        #region 属性
        // 用于UI绑定的数据属性，通过SetProperty实现变更通知。
        public ObservableCollection<RoleDto> Roles
        {
            get => _roles;
            set => SetProperty(ref _roles, value);
        }

        public RoleDto SelectedRole
        {
            get => _selectedRole;
            set => SetProperty(ref _selectedRole, value);
        }

        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        public string SearchRoleName
        {
            get => _searchRoleName;
            set => SetProperty(ref _searchRoleName, value);
        }

        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }
        #endregion

        #region 命令
        // 用于UI绑定和触发ViewModel操作的命令。
        public RelayCommand LoadDataCommand { get; }
        public RelayCommand SearchCommand { get; }
        public RelayCommand AddCommand { get; }
        public RelayCommand EditCommand { get; }
        public RelayCommand DeleteCommand { get; }
        public RelayCommand FirstPageCommand { get; }
        public RelayCommand PreviousPageCommand { get; }
        public RelayCommand NextPageCommand { get; }
        public RelayCommand LastPageCommand { get; }
        #endregion

        #region 方法
        // 加载角色数据，重置到第一页并触发搜索。
        private async Task LoadRolesAsync()
        {
            CurrentPage = 1;
            await SearchRolesAsync();
        }

        // 异步搜索角色数据，并更新分页信息。
        private async Task SearchRolesAsync()
        {
            try
            {
                IsLoading = true;
                var searchDto = new SearchRoleDto
                {
                    RoleName = SearchRoleName,
                    PageIndex = CurrentPage,
                    PageSize = PageSize
                };

                var result = await _roleService.SearchRolesAsync(searchDto);

                Roles.Clear();
                if (result.Data != null)
                {
                    foreach (var role in result.Data)
                    {
                        Roles.Add(role);
                    }
                }
                TotalCount = result.TotalCount;
                TotalPages = result.TotalPage;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"获取角色数据失败: {ex.Message}", "错误");
            }
            finally
            {
                IsLoading = false;
            }
        }

        private void AddRole()
        {
            var addRoleWindow = new WPFServices.Views.DomainViews.AddRoleWindow();
            addRoleWindow.Owner = System.Windows.Application.Current.MainWindow;

            if (addRoleWindow.ShowDialog() == true)
            {
                // 如果成功添加，刷新列表
                _ = SearchRolesAsync();
            }
        }

        private void EditRole()
        {
            if (SelectedRole == null) return;

            var editRoleWindow = new WPFServices.Views.DomainViews.EditRoleWindow(SelectedRole);
            editRoleWindow.Owner = System.Windows.Application.Current.MainWindow;

            if (editRoleWindow.ShowDialog() == true)
            {
                // 如果成功编辑，刷新列表
                _ = SearchRolesAsync();
            }
        }

        private async Task DeleteRoleAsync()
        {
            if (SelectedRole == null) return;

            var result = System.Windows.MessageBox.Show(
                $"确定要删除角色 '{SelectedRole.RoleName}' 吗？",
                "确认删除",
                System.Windows.MessageBoxButton.YesNo,
                System.Windows.MessageBoxImage.Question);

            if (result == System.Windows.MessageBoxResult.Yes)
            {
                try
                {
                    await _roleService.DeleteRoleAsync(SelectedRole.Id);
                    await SearchRolesAsync(); // 删除后重新加载当前页
                    System.Windows.MessageBox.Show("删除成功！");
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show($"删除失败: {ex.Message}", "错误");
                }
            }
        }

        // 跳转到第一页。
        private void GoToFirstPage()
        {
            CurrentPage = 1;
            _ = SearchRolesAsync();
        }

        // 跳转到上一页。
        private void GoToPreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                _ = SearchRolesAsync();
            }
        }

        // 跳转到下一页。
        private void GoToNextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                _ = SearchRolesAsync();
            }
        }

        // 跳转到最后一页。
        private void GoToLastPage()
        {
            CurrentPage = TotalPages;
            _ = SearchRolesAsync();
        }
        #endregion
    }
}